<?php
class Utility_model extends CI_Model {
    function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
    }
    //Tạo số random
    function random()
    {
        return md5(rand(1000000,9999999).date("YmdHis"));
    }
    function checkExist($value,$fieldname,$tablename){
    	if($this->db->field_exists($fieldname, $tablename)){
	    	$this->db->where($fieldname,$value);
	    	$query = $this->db->get($tablename);
	    	$result = $query->row();
	    	if($result) return "false_value";
	    	else return "true";
    	}
    	else return "false_field"; 
    }

    //Upload file
    //    $filetype: Loại file
    //    $filename: name
    //    $userID: id
    //    $chuyenmuc: loại chuyên mục('tintuc' hoặc 'video')
    // return dữ liệu của file upload
    public function doUpload($filetype, $filename, $userID, $chuyenmuc)
    {
        $userName=$this->user_model->getUsername($userID);
        $date=date("d.m.Y");
        switch ($filetype)
        {
            case 'image':
                $path="./uploads/$chuyenmuc/images/$userName/$date";
                if(!file_exists($path))
                {
                   mkdir($path,777,TRUE);
                }
                $config['upload_path'] = $path;              
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '2000';
                break;
            case 'video':
                $path="./uploads/$chuyenmuc/videos/$userName/$date";
                if(!file_exists($path))
                {
                   mkdir($path,777,TRUE);
                }
                $config['upload_path'] = $path;
                $config['allowed_types'] = 'mp4|flv';
                $config['max_size'] = '50240';
                break;
            case 'flash':
                $path="./uploads/$chuyenmuc/flash/$userName/$date";
                if(!file_exists($path))
                {
                   mkdir($path,777,TRUE);
                }
                $config['upload_path'] = $path;
                $config['allowed_types'] = 'swf';
                $config['max_size'] = '50240';
                break;

        }
        $this->load->library('upload', $config);
        $this->upload->initialize($config);
        if (!$this->upload->do_upload($filename))
        {
            $this->error = $this->upload->display_errors();
            return false;
        } else
        {
            $data = $this->upload->data();
            $data['duongdan']=$path.'/'.$data['file_name'];
            return $data;
        }
    }

}
?>